const exec = require('child_process').exec;
const fs = require('fs-extra');
const { setTimeout } = require('timers');
function getHostList() {
  // 群辉的反向代理
  const data = fs.readFileSync('/usr/syno/etc/certificate/_archive/INFO', 'utf8')
  let hostList = ['gepik.top','qh.gepik.top'];
    const hostObj = JSON.parse(data)
    for (const key of Object.keys(hostObj)) {
      const services = hostObj[key].services;
      for (const service of services) {
        if(service.display_name.includes('gepik')) {
          hostList.push(service.display_name.split(':')[0])
        }
      }
    }
    // nginxwebui的反向代理 /volume1/docker/nginxWebUI/conf.d
    const files = fs.readdirSync('/volume1/docker/nginxWebUI/conf.d')
    for (const file of files) {
      if(file.includes('gepik')) {
        hostList.push(file.replace('.conf',''))
      }
    }
    compare(hostList);
}
function compare(hostList) {
  fs.readFile('./hostList.txt', 'utf8', (err, data) => {
    const prevHostTxt = data;
    const currentHostTxt = hostList.join('\n');
    if(prevHostTxt===currentHostTxt) {
      console.log('hostList未发生变化');
    } else {
      console.log('hostList发生变化');
      fs.writeFileSync('./hostList.txt', currentHostTxt);
      setTimeout(()=>{
        backupToGit();
      },1000)
    }
    
    
  })
}

function backupToGit() {
  exec(`git add . && git commit -m "update hostList"`, (error, stdout, stderr) => {
    if(!error) {
      console.log('git commit 成功');
      exec(`git push`, (error, stdout, stderr) => {
        if(error) {
          console.log('git push 失败',error);
          console.log('强制推送')
          exec(`git push -f`,error=>{
            if(error) {
              console.log('强制推送失败',error);
            } else {
              console.log('强制推送成功');
            }
          })
        }else {
          console.log('git push 成功');
        }
      })
    } else {
      console.log('git commit 失败',error);
    }
  })
 
}

getHostList();

